package com.zhentao.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.common.Result;
import com.zhentao.dto.QueryConditionDto;
import com.zhentao.dto.SummaryQueryResultDto;
import com.zhentao.pojo.DataCollection;
import com.zhentao.service.ArimaPredictionService;
import com.zhentao.service.DataQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.math.BigDecimal;

@RestController
@RequestMapping("/api/anomaly-query")
@CrossOrigin(origins = "*")
public class AnomalyQueryController {

    @Autowired
    private DataQueryService dataQueryService;
    
    @Autowired
    private ArimaPredictionService arimaPredictionService;

    // ==================== 基础查询接口 ====================
    
    @PostMapping("/summary")
    public Result<List<SummaryQueryResultDto>> summary(@RequestBody QueryConditionDto body) {
        try {
            return Result.success("汇总查询成功", dataQueryService.summaryQuery(body));
        } catch (Exception e) {
            return Result.error("汇总查询失败：" + e.getMessage());
        }
    }

    @PostMapping("/data")
    public Result<IPage<DataCollection>> data(@RequestBody QueryConditionDto body) {
        try {
            return Result.success("数据查询成功", dataQueryService.dataQuery(body));
        } catch (Exception e) {
            return Result.error("数据查询失败：" + e.getMessage());
        }
    }

    @PostMapping("/raw-data")
    public Result<IPage<DataCollection>> raw(@RequestBody QueryConditionDto body) {
        try {
            return Result.success("原始数据查询成功", dataQueryService.rawDataQuery(body));
        } catch (Exception e) {
            return Result.error("原始数据查询失败：" + e.getMessage());
        }
    }

    @PostMapping("/export")
    public Result<Object> export(@RequestBody QueryConditionDto body, @RequestParam String exportType) {
        try {
            return Result.success("导出成功", dataQueryService.exportQueryResult(body, exportType));
        } catch (Exception e) {
            return Result.error("导出失败：" + e.getMessage());
        }
    }

    @GetMapping("/group-dimensions")
    public Result<List<String>> groupDimensions(@RequestParam String queryType) {
        try {
            return Result.success("获取分组维度成功", dataQueryService.getAvailableGroupDimensions(queryType));
        } catch (Exception e) {
            return Result.error("获取分组维度失败：" + e.getMessage());
        }
    }

    @GetMapping("/output-fields")
    public Result<List<String>> outputFields(@RequestParam String queryType) {
        try {
            return Result.success("获取输出字段成功", dataQueryService.getAvailableOutputFields(queryType));
        } catch (Exception e) {
            return Result.error("获取输出字段失败：" + e.getMessage());
        }
    }

    // ==================== 数据预测接口 ====================
    
    /**
     * 总金额预测 - 基于ARIMA模型
     */
    @PostMapping("/prediction/total-amount")
    public Result<Map<String, Object>> totalAmountPrediction(@RequestBody Map<String, Object> request) {
        try {
            // 从请求中获取预测参数
            int forecastPeriods = (int) request.getOrDefault("forecastPeriods", 6); // 默认预测6个周期
            
            // 构建查询条件
            QueryConditionDto condition = new QueryConditionDto();
            condition.setQueryType("SUMMARY_QUERY");
            condition.setGroupDimensions(List.of("customs_area")); // 按关区分组
            condition.setOutputFields(List.of("amount_cny", "amount_usd", "goods_quantity"));
            
            // 从请求中获取过滤条件
            if (request.containsKey("importExportType")) {
                condition.setImportExportType((String) request.get("importExportType"));
            }
            if (request.containsKey("customsArea")) {
                condition.setCustomsArea((String) request.get("customsArea"));
            }
            
            // 执行ARIMA预测
            Map<String, Object> predictionResult = arimaPredictionService.predictTotalAmount(condition, forecastPeriods);
            
            // 生成前端表格需要的预测数据
            List<Map<String, Object>> tableData = arimaPredictionService.generatePredictionTableData(forecastPeriods);
            predictionResult.put("tableData", tableData);
            
            return Result.success("总金额预测成功", predictionResult);
            
        } catch (Exception e) {
            return Result.error("总金额预测失败：" + e.getMessage());
        }
    }

    /**
     * 分组预测 - 基于ARIMA模型
     */
    @PostMapping("/prediction/grouped")
    public Result<List<Map<String, Object>>> groupedPrediction(@RequestBody Map<String, Object> request) {
        try {
            // 从请求中获取预测参数
            int forecastPeriods = (int) request.getOrDefault("forecastPeriods", 6); // 默认预测6个周期
            
            // 构建查询条件
            QueryConditionDto condition = new QueryConditionDto();
            condition.setQueryType("SUMMARY_QUERY");
            
            // 从请求中获取分组维度
            if (request.containsKey("groupDimensions")) {
                @SuppressWarnings("unchecked")
                List<String> groupDims = (List<String>) request.get("groupDimensions");
                condition.setGroupDimensions(groupDims);
            } else {
                // 默认按关区分组
                condition.setGroupDimensions(List.of("customs_area"));
            }
            
            condition.setOutputFields(List.of("amount_cny", "amount_usd", "goods_quantity"));
            
            // 从请求中获取过滤条件
            if (request.containsKey("importExportType")) {
                condition.setImportExportType((String) request.get("importExportType"));
            }
            if (request.containsKey("customsArea")) {
                condition.setCustomsArea((String) request.get("customsArea"));
            }
            
            // 执行分组预测
            List<Map<String, Object>> predictionResults = arimaPredictionService.predictGrouped(condition, forecastPeriods);
            
            // 为每个分组生成表格数据
            for (Map<String, Object> result : predictionResults) {
                if ("completed".equals(result.get("status"))) {
                    List<Map<String, Object>> tableData = arimaPredictionService.generatePredictionTableData(forecastPeriods);
                    result.put("tableData", tableData);
                }
            }
            
            return Result.success("分组预测成功", predictionResults);
            
        } catch (Exception e) {
            return Result.error("分组预测失败：" + e.getMessage());
        }
    }

    // ==================== 异动监测接口 ====================
    
    /**
     * 重点商品监测 - 基于真实数据计算异动
     */
    @PostMapping("/monitoring/key-commodity")
    public Result<Map<String, Object>> keyCommodityMonitoring(@RequestBody Map<String, Object> request) {
        try {
            // 构建查询条件 - 只使用基础字段
            QueryConditionDto condition = new QueryConditionDto();
            condition.setQueryType("SUMMARY_QUERY");
            // 只使用基础字段进行分组
            condition.setGroupDimensions(List.of("customs_area"));
            condition.setOutputFields(List.of("amount_cny", "amount_usd", "goods_quantity"));
            
            // 从请求中获取过滤条件
            if (request.containsKey("importExportType")) {
                condition.setImportExportType((String) request.get("importExportType"));
            }
            if (request.containsKey("customsArea")) {
                condition.setCustomsArea((String) request.get("customsArea"));
            }
            
            // 执行查询获取真实数据
            List<SummaryQueryResultDto> summaryResults = dataQueryService.summaryQuery(condition);
            
            // 分析异动（这里需要根据实际业务规则实现）
            Map<String, Object> result = new HashMap<>();
            result.put("importData", new ArrayList<>());
            result.put("exportData", new ArrayList<>());
            
            // 根据进出口类型分类数据
            for (SummaryQueryResultDto summary : summaryResults) {
                if ("IMPORT".equals(summary.getImportExportType())) {
                    ((List) result.get("importData")).add(convertToMonitoringResult(summary));
                } else if ("EXPORT".equals(summary.getImportExportType())) {
                    ((List) result.get("exportData")).add(convertToMonitoringResult(summary));
                }
            }
            
            return Result.success("重点商品监测成功", result);
        } catch (Exception e) {
            return Result.error("重点商品监测失败：" + e.getMessage());
        }
    }

    /**
     * 口岸异动监测 - 基于真实数据计算异动
     */
    @PostMapping("/monitoring/port")
    public Result<Map<String, Object>> portMonitoring(@RequestBody Map<String, Object> request) {
        try {
            // 构建查询条件 - 只使用基础字段
            QueryConditionDto condition = new QueryConditionDto();
            condition.setQueryType("SUMMARY_QUERY");
            // 只使用基础字段进行分组
            condition.setGroupDimensions(List.of("customs_area"));
            condition.setOutputFields(List.of("amount_cny", "amount_usd", "goods_quantity"));
            
            // 从请求中获取过滤条件
            if (request.containsKey("customsArea")) {
                condition.setCustomsArea((String) request.get("customsArea"));
            }
            
            // 执行查询获取真实数据
            List<SummaryQueryResultDto> summaryResults = dataQueryService.summaryQuery(condition);
            
            // 分析异动
            Map<String, Object> result = new HashMap<>();
            result.put("declarationCustoms", new ArrayList<>());
            result.put("entryExitCustoms", new ArrayList<>());
            
            // 这里需要根据实际业务逻辑区分申报口岸和进出境口岸
            for (SummaryQueryResultDto summary : summaryResults) {
                // 暂时都放入申报口岸，实际需要根据业务规则区分
                ((List) result.get("declarationCustoms")).add(convertToPortMonitoringResult(summary));
            }
            
            return Result.success("口岸异动监测成功", result);
        } catch (Exception e) {
            return Result.error("口岸异动监测失败：" + e.getMessage());
        }
    }

    /**
     * 重点业态监测 - 基于真实数据计算异动
     */
    @PostMapping("/monitoring/business-type")
    public Result<List<Map<String, Object>>> businessTypeMonitoring(@RequestBody Map<String, Object> request) {
        try {
            // 构建查询条件 - 只使用基础字段
            QueryConditionDto condition = new QueryConditionDto();
            condition.setQueryType("SUMMARY_QUERY");
            // 只使用基础字段进行分组
            condition.setGroupDimensions(List.of("customs_area"));
            condition.setOutputFields(List.of("amount_cny", "amount_usd", "goods_quantity"));
            
            // 从请求中获取过滤条件
            if (request.containsKey("customsArea")) {
                condition.setCustomsArea((String) request.get("customsArea"));
            }
            
            // 执行查询获取真实数据
            List<SummaryQueryResultDto> summaryResults = dataQueryService.summaryQuery(condition);
            
            // 转换为监测结果格式
            List<Map<String, Object>> results = new ArrayList<>();
            for (SummaryQueryResultDto summary : summaryResults) {
                results.add(convertToBusinessTypeMonitoringResult(summary));
            }
            
            return Result.success("重点业态监测成功", results);
        } catch (Exception e) {
            return Result.error("重点业态监测失败：" + e.getMessage());
        }
    }

    /**
     * 地区监测 - 基于真实数据计算异动
     */
    @PostMapping("/monitoring/region")
    public Result<List<Map<String, Object>>> regionMonitoring(@RequestBody Map<String, Object> request) {
        try {
            // 构建查询条件 - 只使用基础字段
            QueryConditionDto condition = new QueryConditionDto();
            condition.setQueryType("SUMMARY_QUERY");
            // 只使用基础字段进行分组
            condition.setGroupDimensions(List.of("customs_area"));
            condition.setOutputFields(List.of("amount_cny", "amount_usd", "goods_quantity"));
            
            // 从请求中获取过滤条件
            if (request.containsKey("customsArea")) {
                condition.setCustomsArea((String) request.get("customsArea"));
            }
            
            // 执行查询获取真实数据
            List<SummaryQueryResultDto> summaryResults = dataQueryService.summaryQuery(condition);
            
            // 转换为监测结果格式
            List<Map<String, Object>> results = new ArrayList<>();
            for (SummaryQueryResultDto summary : summaryResults) {
                results.add(convertToRegionMonitoringResult(summary));
            }
            
            return Result.success("地区监测成功", results);
        } catch (Exception e) {
            return Result.error("地区监测失败：" + e.getMessage());
        }
    }

    /**
     * 国别监测 - 基于真实数据计算异动
     */
    @PostMapping("/monitoring/country")
    public Result<List<Map<String, Object>>> countryMonitoring(@RequestBody Map<String, Object> request) {
        try {
            // 构建查询条件 - 只使用基础字段
            QueryConditionDto condition = new QueryConditionDto();
            condition.setQueryType("SUMMARY_QUERY");
            // 只使用基础字段进行分组
            condition.setGroupDimensions(List.of("customs_area"));
            condition.setOutputFields(List.of("amount_cny", "amount_usd", "goods_quantity"));
            
            // 从请求中获取过滤条件
            if (request.containsKey("customsArea")) {
                condition.setCustomsArea((String) request.get("customsArea"));
            }
            
            // 执行查询获取真实数据
            List<SummaryQueryResultDto> summaryResults = dataQueryService.summaryQuery(condition);
            
            // 转换为监测结果格式
            List<Map<String, Object>> results = new ArrayList<>();
            for (SummaryQueryResultDto summary : summaryResults) {
                results.add(convertToCountryMonitoringResult(summary));
            }
            
            return Result.success("国别监测成功", results);
        } catch (Exception e) {
            return Result.error("国别监测失败：" + e.getMessage());
        }
    }

    /**
     * 钻取分析 - 基于真实数据进行钻取
     */
    @PostMapping("/drill-down")
    public Result<List<Map<String, Object>>> drillDownAnalysis(@RequestBody Map<String, Object> request) {
        try {
            // 支持两种参数格式
            String dimension = (String) request.get("dimension");
            String value = (String) request.get("value");
            
            // 新的参数格式支持
            List<String> drillPath = (List<String>) request.get("drillPath");
            Integer currentLevel = (Integer) request.get("currentLevel");
            Map<String, Object> filters = (Map<String, Object>) request.get("filters");
            
            // 如果使用新的参数格式
            if (drillPath != null && currentLevel != null && currentLevel < drillPath.size()) {
                dimension = drillPath.get(currentLevel);
                
                // 从filters中获取对应的值
                if (filters != null) {
                    switch (dimension) {
                        case "commodity":
                        case "hs_code":
                            value = (String) filters.get("hsCode");
                            break;
                        case "enterprise":
                        case "enterprise_name":
                            value = (String) filters.get("enterpriseName");
                            break;
                        case "trade_method":
                            value = (String) filters.get("tradeMethod");
                            break;
                        case "country":
                        case "country_code":
                            value = (String) filters.get("countryCode");
                            break;
                        case "region":
                        case "region_code":
                            value = (String) filters.get("regionCode");
                            break;
                        case "port":
                        case "port_code":
                            value = (String) filters.get("portCode");
                            break;
                        case "customs_area":
                            value = (String) filters.get("customsArea");
                            break;
                        case "import_export_type":
                            value = (String) filters.get("importExportType");
                            break;
                        default:
                            value = null;
                    }
                }
            }
            
            if (dimension == null || value == null) {
                return Result.error("钻取维度或值不能为空");
            }
            
            // 构建查询条件
            QueryConditionDto condition = new QueryConditionDto();
            condition.setQueryType("SUMMARY_QUERY");
            
            // 根据钻取维度设置合适的分组字段
            List<String> groupDimensions = getDrillDownGroupDimensions(dimension);
            condition.setGroupDimensions(groupDimensions);
            condition.setOutputFields(List.of("amount_cny", "amount_usd", "goods_quantity", "declare_count", "record_count"));
            
            // 应用filters中的过滤条件
            if (filters != null) {
                if (filters.containsKey("importExportType")) {
                    condition.setImportExportType((String) filters.get("importExportType"));
                }
                if (filters.containsKey("customsArea")) {
                    condition.setCustomsArea((String) filters.get("customsArea"));
                }
                if (filters.containsKey("startDate")) {
                    condition.setStartDate(parseDate((String) filters.get("startDate")));
                }
                if (filters.containsKey("endDate")) {
                    condition.setEndDate(parseDate((String) filters.get("endDate")));
                }
            }
            
            // 根据钻取条件设置过滤
            switch (dimension) {
                // 地理位置维度
                case "country_code":
                case "country":
                    condition.setCountryCode(value);
                    break;
                case "region_code":
                case "region":
                    condition.setRegionCode(value);
                    break;
                case "port_code":
                case "port":
                    condition.setPortCode(value);
                    break;
                case "customs_area":
                    condition.setCustomsArea(value);
                    break;
                
                // 商品维度
                case "hs_code":
                case "commodity":
                    condition.setHsCode(value);
                    break;
                case "goods_name":
                    condition.setGoodsName(value);
                    break;
                
                // 企业维度
                case "enterprise_name":
                case "enterprise":
                    condition.setEnterpriseName(value);
                    break;
                case "enterprise_code":
                    condition.setEnterpriseCode(value);
                    break;
                
                // 贸易维度
                case "trade_method":
                case "business_type":
                    condition.setTradeMethod(value);
                    break;
                case "transport_mode":
                    condition.setTransportMode(value);
                    break;
                
                // 进出口类型
                case "import_export_type":
                    condition.setImportExportType(value);
                    break;
                
                // 时间维度
                case "create_time":
                case "customs_clearance_date":
                    // 时间范围处理，这里简化处理
                    // 实际应用中需要解析时间字符串并设置范围
                    break;
                
                // 金额和数量维度
                case "amount_category":
                    // 金额类别过滤，需要根据value设置金额范围
                    setAmountRangeFilter(condition, value);
                    break;
                case "quantity_category":
                    // 数量类别过滤，需要根据value设置数量范围
                    setQuantityRangeFilter(condition, value);
                    break;
                
                // 风险维度
                case "risk_level":
                    // 风险等级过滤，需要根据value设置相应的条件
                    setRiskLevelFilter(condition, value);
                    break;
                
                default:
                    return Result.error("不支持的钻取维度：" + dimension);
            }
            
            // 执行查询获取真实数据
            List<SummaryQueryResultDto> summaryResults = dataQueryService.summaryQuery(condition);
            
            // 转换为钻取结果格式
            List<Map<String, Object>> results = new ArrayList<>();
            for (SummaryQueryResultDto summary : summaryResults) {
                results.add(convertToDrillDownResult(summary, dimension, value));
            }
            
            return Result.success("钻取分析成功", results);
        } catch (Exception e) {
            return Result.error("钻取分析失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取钻取分析的分组维度
     */
    private List<String> getDrillDownGroupDimensions(String dimension) {
        switch (dimension) {
            // 地理位置维度钻取
            case "country_code":
            case "country":
                return List.of("region_code", "port_code", "customs_area");
            case "region_code":
            case "region":
                return List.of("port_code", "customs_area", "enterprise_name");
            case "port_code":
            case "port":
                return List.of("customs_area", "enterprise_name", "trade_method");
            case "customs_area":
                return List.of("port_code", "enterprise_name", "trade_method");
            
            // 商品维度钻取
            case "hs_code":
            case "commodity":
                return List.of("country_code", "region_code", "port_code");
            case "goods_name":
                return List.of("hs_code", "country_code", "enterprise_name");
            
            // 企业维度钻取
            case "enterprise_name":
            case "enterprise":
                return List.of("port_code", "trade_method", "hs_code");
            case "enterprise_code":
                return List.of("enterprise_name", "port_code", "trade_method");
            
            // 贸易维度钻取
            case "trade_method":
            case "business_type":
                return List.of("country_code", "region_code", "port_code");
            case "transport_mode":
                return List.of("port_code", "country_code", "enterprise_name");
            
            // 进出口类型钻取
            case "import_export_type":
                return List.of("country_code", "region_code", "port_code");
            
            // 默认分组
            default:
                return List.of("customs_area", "import_export_type");
        }
    }
    
    /**
     * 设置金额范围过滤
     */
    private void setAmountRangeFilter(QueryConditionDto condition, String amountCategory) {
        switch (amountCategory) {
            case "大额":
                condition.setMinAmount(1000000.0);
                break;
            case "中额":
                condition.setMinAmount(100000.0);
                condition.setMaxAmount(1000000.0);
                break;
            case "小额":
                condition.setMaxAmount(100000.0);
                break;
        }
    }
    
    /**
     * 设置数量范围过滤
     */
    private void setQuantityRangeFilter(QueryConditionDto condition, String quantityCategory) {
        switch (quantityCategory) {
            case "大量":
                condition.setMinAmount(10000.0);
                break;
            case "中量":
                condition.setMinAmount(1000.0);
                condition.setMaxAmount(10000.0);
                break;
            case "少量":
                condition.setMaxAmount(1000.0);
                break;
        }
    }
    
    /**
     * 设置风险等级过滤
     */
    private void setRiskLevelFilter(QueryConditionDto condition, String riskLevel) {
        switch (riskLevel) {
            case "高风险":
                condition.setEnterpriseCreditLevel("C");
                condition.setMinAmount(1000000.0);
                break;
            case "中风险":
                condition.setEnterpriseCreditLevel("B");
                break;
            case "低风险":
                condition.setEnterpriseCreditLevel("A");
                condition.setMaxAmount(100000.0);
                break;
        }
    }
    
    // ==================== 辅助方法 ====================
    
    /**
     * 转换为商品监测结果
     */
    private Map<String, Object> convertToMonitoringResult(SummaryQueryResultDto summary) {
        Map<String, Object> result = new HashMap<>();
        result.put("serialNo", 1); // 需要根据实际情况生成
        result.put("commodityName", summary.getGoodsName() != null ? summary.getGoodsName() : summary.getHsCode());
        result.put("amount", summary.getAmountCny());
        result.put("yoyChange", summary.getAmountYoyChange());
        result.put("momChange", summary.getAmountMomChange());
        result.put("quantity", summary.getGoodsQuantity());
        result.put("quantityYoyChange", summary.getQuantityYoyChange());
        result.put("quantityMomChange", summary.getQuantityMomChange());
        result.put("isAlert", summary.getIsAnomaly());
        return result;
    }
    
    /**
     * 转换为口岸监测结果
     */
    private Map<String, Object> convertToPortMonitoringResult(SummaryQueryResultDto summary) {
        Map<String, Object> result = new HashMap<>();
        result.put("serialNo", 1); // 需要根据实际情况生成
        result.put("port", summary.getPortName() != null ? summary.getPortName() : summary.getPortCode());
        result.put("importExportAmount", summary.getAmountCny());
        result.put("importExportYoyChange", summary.getAmountYoyChange());
        result.put("importExportMomChange", summary.getAmountMomChange());
        
        // 根据进出口类型正确设置进口和出口金额
        if ("IMPORT".equals(summary.getImportExportType())) {
            result.put("importAmount", summary.getAmountCny());
            result.put("importYoyChange", summary.getAmountYoyChange());
            result.put("importMomChange", summary.getAmountMomChange());
            result.put("exportAmount", BigDecimal.ZERO);
            result.put("exportYoyChange", 0.0);
            result.put("exportMomChange", 0.0);
        } else if ("EXPORT".equals(summary.getImportExportType())) {
            result.put("importAmount", BigDecimal.ZERO);
            result.put("importYoyChange", 0.0);
            result.put("importMomChange", 0.0);
            result.put("exportAmount", summary.getAmountCny());
            result.put("exportYoyChange", summary.getAmountYoyChange());
            result.put("exportMomChange", summary.getAmountMomChange());
        } else {
            // 如果类型不明确，平均分配
            BigDecimal halfAmount = summary.getAmountCny().divide(BigDecimal.valueOf(2), 2, BigDecimal.ROUND_HALF_UP);
            result.put("importAmount", halfAmount);
        result.put("importYoyChange", summary.getAmountYoyChange());
        result.put("importMomChange", summary.getAmountMomChange());
            result.put("exportAmount", halfAmount);
        result.put("exportYoyChange", summary.getAmountYoyChange());
        result.put("exportMomChange", summary.getAmountMomChange());
        }
        
        result.put("isAlert", summary.getIsAnomaly());
        return result;
    }
    
    /**
     * 转换为业态监测结果
     */
    private Map<String, Object> convertToBusinessTypeMonitoringResult(SummaryQueryResultDto summary) {
        Map<String, Object> result = new HashMap<>();
        result.put("serialNo", 1); // 需要根据实际情况生成
        result.put("tradeMethod", summary.getTradeMethod());
        result.put("importExportAmount", summary.getAmountCny());
        result.put("importExportYoyChange", summary.getAmountYoyChange());
        result.put("importExportMomChange", summary.getAmountMomChange());
        
        // 根据进出口类型正确设置进口和出口金额
        if ("IMPORT".equals(summary.getImportExportType())) {
            result.put("importAmount", summary.getAmountCny());
            result.put("importYoyChange", summary.getAmountYoyChange());
            result.put("importMomChange", summary.getAmountMomChange());
            result.put("exportAmount", BigDecimal.ZERO);
            result.put("exportYoyChange", 0.0);
            result.put("exportMomChange", 0.0);
        } else if ("EXPORT".equals(summary.getImportExportType())) {
            result.put("importAmount", BigDecimal.ZERO);
            result.put("importYoyChange", 0.0);
            result.put("importMomChange", 0.0);
            result.put("exportAmount", summary.getAmountCny());
            result.put("exportYoyChange", summary.getAmountYoyChange());
            result.put("exportMomChange", summary.getAmountMomChange());
        } else {
            // 如果类型不明确，平均分配
            BigDecimal halfAmount = summary.getAmountCny().divide(BigDecimal.valueOf(2), 2, BigDecimal.ROUND_HALF_UP);
            result.put("importAmount", halfAmount);
        result.put("importYoyChange", summary.getAmountYoyChange());
        result.put("importMomChange", summary.getAmountMomChange());
            result.put("exportAmount", halfAmount);
        result.put("exportYoyChange", summary.getAmountYoyChange());
        result.put("exportMomChange", summary.getAmountMomChange());
        }
        
        result.put("isAlert", summary.getIsAnomaly());
        return result;
    }
    
    /**
     * 转换为地区监测结果
     */
    private Map<String, Object> convertToRegionMonitoringResult(SummaryQueryResultDto summary) {
        Map<String, Object> result = new HashMap<>();
        result.put("serialNo", 1); // 需要根据实际情况生成
        result.put("region", summary.getRegionName() != null ? summary.getRegionName() : summary.getRegionCode());
        result.put("importExportAmount", summary.getAmountCny());
        result.put("importExportYoyChange", summary.getAmountYoyChange());
        result.put("importExportMomChange", summary.getAmountMomChange());
        
        // 根据进出口类型正确设置进口和出口金额
        if ("IMPORT".equals(summary.getImportExportType())) {
            result.put("importAmount", summary.getAmountCny());
            result.put("importYoyChange", summary.getAmountYoyChange());
            result.put("importMomChange", summary.getAmountMomChange());
            result.put("exportAmount", BigDecimal.ZERO);
            result.put("exportYoyChange", 0.0);
            result.put("exportMomChange", 0.0);
        } else if ("EXPORT".equals(summary.getImportExportType())) {
            result.put("importAmount", BigDecimal.ZERO);
            result.put("importYoyChange", 0.0);
            result.put("importMomChange", 0.0);
            result.put("exportAmount", summary.getAmountCny());
            result.put("exportYoyChange", summary.getAmountYoyChange());
            result.put("exportMomChange", summary.getAmountMomChange());
        } else {
            // 如果类型不明确，平均分配
            BigDecimal halfAmount = summary.getAmountCny().divide(BigDecimal.valueOf(2), 2, BigDecimal.ROUND_HALF_UP);
            result.put("importAmount", halfAmount);
        result.put("importYoyChange", summary.getAmountYoyChange());
        result.put("importMomChange", summary.getAmountMomChange());
            result.put("exportAmount", halfAmount);
        result.put("exportYoyChange", summary.getAmountYoyChange());
        result.put("exportMomChange", summary.getAmountMomChange());
        }
        
        result.put("isAlert", summary.getIsAnomaly());
        return result;
    }
    
    /**
     * 转换为国别监测结果
     */
    private Map<String, Object> convertToCountryMonitoringResult(SummaryQueryResultDto summary) {
        Map<String, Object> result = new HashMap<>();
        result.put("serialNo", 1); // 需要根据实际情况生成
        // 使用本模块DTO可用字段：优先 groupValue，其次 customsArea，再次 countryName/countryCode
        String countryLike = summary.getGroupValue();
        if (countryLike == null || countryLike.isEmpty()) {
            countryLike = summary.getCustomsArea();
        }
        if ((countryLike == null || countryLike.isEmpty())) {
            countryLike = summary.getCountryName() != null ? summary.getCountryName() : summary.getCountryCode();
        }
        result.put("country", countryLike != null ? countryLike : "未知");
        result.put("importExportAmount", summary.getAmountCny());
        result.put("importExportYoyChange", summary.getAmountYoyChange());
        result.put("importExportMomChange", summary.getAmountMomChange());
        
        // 根据进出口类型正确设置进口和出口金额
        if ("IMPORT".equals(summary.getImportExportType())) {
            result.put("importAmount", summary.getAmountCny());
            result.put("importYoyChange", summary.getAmountYoyChange());
            result.put("importMomChange", summary.getAmountMomChange());
            result.put("exportAmount", BigDecimal.ZERO);
            result.put("exportYoyChange", 0.0);
            result.put("exportMomChange", 0.0);
        } else if ("EXPORT".equals(summary.getImportExportType())) {
            result.put("importAmount", BigDecimal.ZERO);
            result.put("importYoyChange", 0.0);
            result.put("importMomChange", 0.0);
            result.put("exportAmount", summary.getAmountCny());
            result.put("exportYoyChange", summary.getAmountYoyChange());
            result.put("exportMomChange", summary.getAmountMomChange());
        } else {
            // 如果类型不明确，平均分配
            BigDecimal halfAmount = summary.getAmountCny().divide(BigDecimal.valueOf(2), 2, BigDecimal.ROUND_HALF_UP);
            result.put("importAmount", halfAmount);
        result.put("importYoyChange", summary.getAmountYoyChange());
        result.put("importMomChange", summary.getAmountMomChange());
            result.put("exportAmount", halfAmount);
        result.put("exportYoyChange", summary.getAmountYoyChange());
        result.put("exportMomChange", summary.getAmountMomChange());
        }
        
        result.put("isAlert", summary.getIsAnomaly());
        return result;
    }
    
    /**
     * 转换为钻取分析结果
     */
    private Map<String, Object> convertToDrillDownResult(SummaryQueryResultDto summary, String dimension, String value) {
        Map<String, Object> result = new HashMap<>();
        result.put("dimension", dimension);
        result.put("value", value);
        result.put("amount", summary.getAmountCny());
        result.put("yoyChange", summary.getAmountYoyChange());
        result.put("momChange", summary.getAmountMomChange());
        result.put("quantity", summary.getGoodsQuantity());
        result.put("quantityYoyChange", summary.getQuantityYoyChange());
        result.put("quantityMomChange", summary.getQuantityMomChange());
        return result;
    }

    /**
     * 解析日期字符串
     */
    private Date parseDate(String dateStr) {
        try {
            if (dateStr == null || dateStr.isEmpty()) {
                return null;
            }
            // 简单的日期解析，实际应用中可以使用更复杂的解析逻辑
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr);
        } catch (Exception e) {
            return null;
        }
    }
} 

